#Kiwi Editor is a framework for building WYSIWYG web editors.
#Copyright (C) 2011  Roosevelt de Lima Sardinha

#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#Contact the author at roosevelt1@gmail.com (Roosevelt) 

# == Schema Information
# Schema version: 20101204202135
#
# Table name: profiles
#
#  id          :integer         not null, primary key
#  name        :string(255)
#  description :string(255)
#  created_at  :datetime
#  updated_at  :datetime
#

class Profile < ActiveRecord::Base
  has_many :assoc_profile_types, :dependent => :destroy
  has_many :assoc_workspace_profiles, :dependent => :destroy
  has_many :eo_types, :through => :assoc_profile_types
  has_many :workspaces, :through => :assoc_workspace_profiles
    
  def update_with_json(json)
    self.name = json["name"]
    self.description = json["description"]
    self.save
    # Remove old associations
    AssocProfileType.find_all_by_profile_id(self.id).each do |assoc|
      AssocProfileType.destroy(assoc);
    end
    
    
    # Save new associations
    json["types"].each do |type|
      assoc_profile_type = self.assoc_profile_types.build
      if (!EoType.find_by_type_name(type))
        eo_type = EoType.new
        eo_type.type_name = type
        eo_type.save
        assoc_profile_type.eo_type_id = eo_type.id        
      else
        assoc_profile_type.eo_type_id = EoType.find_by_type_name(type).id    
      end    
      assoc_profile_type.save
    end
    
    
  end
  
  def to_hash
    as_json = ActiveSupport::JSON
    all_type_array = []
    self.eo_types.all.each do |eo_type|      
      all_type_array << eo_type.type_name           
    end   
    
    all_profile_data = {}
    all_profile_data["id"] = self.id
    all_profile_data["name"] = self.name
    all_profile_data["description"] = self.description
    all_profile_data["type"] = all_type_array
    
    return all_profile_data
  end 
         
end
